package org.example;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SocketChannel;

public class ZookeeperClient {
    private SocketChannel socketChannel;

    public void connect(String host, int port) throws IOException {
        try {
            socketChannel = SocketChannel.open();
            socketChannel.connect(new InetSocketAddress(host, port));
            System.out.println("Connected to ZooKeeper server at " + host + ":" + port);
        } catch (IOException e) {
            System.err.println("Failed to connect to ZooKeeper server at " + host + ":" + port);
            throw e;
        }
    }

    public void send(byte[] data) throws IOException {
        if (socketChannel == null || !socketChannel.isOpen()) {
            throw new IllegalStateException("Socket channel is not open");
        }
        try {
            System.out.println("Sending data: " + new String(data));
            socketChannel.write(ByteBuffer.wrap(data));
            System.out.println("Data sent successfully");
        } catch (ClosedChannelException e) {
            System.err.println("Socket channel is closed: " + e.getMessage());
            throw e;
        } catch (IOException e) {
            System.err.println("Failed to send data: " + e.getMessage());
            throw e;
        }
    }

    public void close() throws IOException {
        if (socketChannel != null && socketChannel.isOpen()) {
            socketChannel.close();
            System.out.println("Socket channel closed");
        }
    }

    public static void main(String[] args) {
        ZookeeperClient client = new ZookeeperClient();
        try {
            client.connect("192.168.134.130", 2181); // 替换为实际的主机和端口
            byte[] data = "Hello, ZooKeeper!".getBytes();
            client.send(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
